import { App } from './app';
import Util from './util';
import { Page } from './page';
import 'babel-polyfill';
App.registerRoute({
	name:'employeeshift',
	onLoad:function(context, $container){
		let page = new Page($container);
		page.crudLayout({title: '排班管理'});
	let headers = ['早班(9:00 ~ 15:00)','中(14:00 ~ 22:00)','晚(17:00 ~ 02:00)'];
	let _this = this;
	let table_body = '<ul data-id="{{id}}" data-type="{{type}}"><li title="{{name}}">{{code}}{{name}}</li><li>{{shiftBig}}.{{shiftSmall}}</li><li>{{signIn}}</li><li>{{signOut}}</li><li></li></ul>'
	_this.jobid='';
	_this.users = [];
	_this.startTime = context.params.date||moment().format('YYYY-MM-DD');
	_this.tr_html = function(data){
		let trhtml =''
		$.each(data,(index,item)=>{
			trhtml += Mustache.render(table_body,item)
		})
		return trhtml
	};

	//getdata
	_this.getdata = ()=>{
		let reg_form = [];
		 page.content.find('.tbodydata').each((index,item)=>{
		 	if($(item).data('form')){
		 		reg_form = reg_form.concat(JSON.parse($(item).data('form')))
		 	}
		 });
		 return reg_form
	}

	// 渲染员工
	_this.user_show = (userdata)=>{
			userdata =	userdata.sort((item1,item2)=>item1.name.localeCompare(item2.name,'zh-CN'));
			let t = '<li data-id={{id}} data-type="user" title={{name}}>{{name}}</li>'
			let x = ''
			let lis = ()=>{
				for(let a=0;a<userdata.length;a++){
					let nu = userdata[a]
				let	h = Mustache.render(t,nu)
					x += h
				};
				return '<ul style="list-style:none;text-align:center;width:100%" class="tbodydata">'+x+'</ul>'
			};
			page.content.find('#master_user').html(lis()).find('li').draggable({helper:"clone",opacity: 0.8})
			page.content.find('#master_user').data('form',JSON.stringify(userdata));
		
		}
	
	// 渲染头部
	let toolbarfun = function(time,profession){
		page.content.find('.toop_box').dxToolbar({
			items:[{
				widget:'setDateDay',
				location:'before',
				options:{
					value:time,
					onValueChanged:function(e){
						_this.startTime = e;
						_this.getformdata()
					}
				}
			},
			// {
			// 	widget:"dxDateBox",
			// 	location:'before',
			// 	options:{
			// 		placeholder:'请选择时间',
			// 		type:'date',
			// 		value:time,
			// 		displayFormat: 'yyyy-MM-dd',
			// 		dateSerializationFormat: "yyyy-MM-dd",
			// 		onValueChanged:function(e){
			// 			_this.startTime = e.value;
			// 			_this.getformdata()
			// 		}
			// 	}
			// },
			{
				widget:'dxSelectBox',
				location:'before',
				options:{
					dataSource:profession,
					displayExpr:'name',
					valueExpr:'id',
					value:profession[0].id,
					onValueChanged:function(e){
						_this.jobid = e.value;
						_this.getformdata()
					}
				}

			},{
				widget:'dxButton',
				location:'before',
				options:{
					text:'排班保存',
					onClick:function(e){
						let data = _this.getdata();
						let postdata = {
							date: _this.startTime,
							jobId:_this.jobid,
							shifts:[]
						};
						$(data).each((index,item)=>{
							postdata.shifts.push({
								employeeId:Number(item.id),
								shiftId:Number(item.type)
							})
						})

						$.ajax({url:$.config('apiUrl')+'shift/update',
							type:'post',
							data:JSON.stringify(postdata),
							dataType: "json",
							contentType: "application/json;charset=utf-8"
						}).then(res=>{
							if(res.errcode === 200){
								_this.getformdata()
								new DevExpress.ui.notify({message:'保存成功'},'success',1000)
							}
						})
					}
				}
			},{
				widget:'dxButton',
				location:'after',
				options:{
					text:'月排班表',
					onClick:function(e){
						location.href='#/shift_month'
					}
				}
			}]
		})
	}

	page.content.html('<div style="padding:10px 0;overflow:hidden" ><div class="toop_box col-sm-2"></div></div>'+
				'<div  class="crud-grid container-fluid container" style="padding:0;width:100%">'+
				'<div class="dx-datagrid container container-fluid col-sm-12" style="padding:0;width:100%">'+
				'<div class="col-sm-10"  id="bodyfun" style="padding:0;">'+
				'</div><div class="col-sm-2"  style="padding:0;float:right">'+
				'<div style="border:1px solid #eee;background:#f6f8f8;color:#58666e;text-align:center;width:100%;height:42px;line-height:40px;padding:0;" >'+
				'员工列表'+
				'</div><div style="height:840px;overflow:auto;border-left:1px solid #eee;" id="master_user"  data-type="user"></div></div>'+
				'</div></div>');

	


	let table_header = '<ul style="border:1px solid #eee;border-width:1px 0;line-height:35px">'+
		'<li style="border-left:0px solid #eee;" class="sortName">工号/姓名</li>'+
		'<li style="border-left:1px solid #eee;" title="大/小档">大小档</li>'+
		'<li style="border-left:1px solid #eee;" title="最早签到">签到</li>'+
		'<li style="border-left:1px solid #eee;" title="最晚签退">签退</li>'+
		'<li style="text-align:center;border-left:1px solid #eee;">请假</li></ul>'+
		'<div class="tbodydata" style="text-align:center;overflow:auto;height:326px"></div>';

	let header = (head,da,n)=>{
		n = 100/n;
		return	'<div class="drawbox" style="position:relative;float:left;padding:0;border:1px solid #eee;width:'+n+'%" data-type="'+da+'">'+
		'<div style="border:0px solid #eee;background:#f6f8f8;color:#58666e;text-align:center;width:100%;height:40px;line-height:40px;padding:0" >'+
		head+
		'</div>'+
		'<div style="width:100%;height:400px;border-bottom:1px solid #eee" class="top_data">'+
		table_header+
		'</div>'+
		'<div style="border:0px solid #eee;background:#f6f8f8;color:#58666e;text-align:center;width:100%;height:40px;line-height:40px;padding:0" >'+
		'固定班'+head+
		'</div>'+
		'<div  style="width:100%;height:400px;" class="bottom_data">'+
		table_header+
		'</div></div>'
	    };

	// 拖拽
	_this.domshow = function(element,data){
		if(!data){return false}
		element.data('form',JSON.stringify(data));
		element.html(_this.tr_html(data));
		element.find('ul').draggable({helper:"clone",opacity: 0.8})
		element.find('ul').droppable({
				drop:function(ev,trui){
					let thisid = $(this).data('id'),
					thistype = $(this).data('type'),
					otherid = $(trui.draggable).data('id'),
					othertype = $(trui.draggable).data('type');
					if(thistype == othertype){
						let thisform = JSON.parse($(this).parent('.tbodydata').data('form'));
						let otherdata = '';
						$(_this.users).each((index,item)=>{
							if(item.id == otherid)otherdata =item;
						});

						let otherindex = ''
						$(thisform).each((index,item)=>{
							if(item&&item.id == thisid){
							otherindex = index;
							}
						})

						otherdata.type =  thistype;
						$(thisform).each((index,item)=>{
							if(item&&item.id == otherid){
								thisform.splice(index,1)
							}
						})
						thisform.splice(otherindex,0,otherdata)
						_this.domshow($(this).parent('.tbodydata'),thisform)

					}

				}
			})	
	}

	// 渲染内容	
	_this.content_append = function(){
		page.content.find('.drawbox,#master_user').droppable({
			drop:function(e,ui){
				let drawtype = $(this).data('type');
				let ultype = ui.draggable.context.dataset.type
				let id = ui.draggable.context.dataset.id;
				if(drawtype == ultype){return false};
				let data = '';
					$.each(_this.users,function(index,item){
						if(item.id==id)data=item
					});
					data.type=drawtype

					let grid = '',doms='';
					if(drawtype == 'user'){
						doms = $(this);
						grid = doms.data('form');
						if(grid){
							grid = JSON.parse(grid);//获取数据
							grid.unshift(data)
						}else{
							grid = [data]
						}
					_this.user_show(grid)
					
					}else{
						if(!data.isFix){
							doms = $(this).find('.top_data .tbodydata')
						}else{
							doms = $(this).find('.bottom_data .tbodydata')
						};

					grid = doms.data('form')
						if(grid){
							grid = JSON.parse(grid);//获取数据
							grid.push(data)
						}else{
							grid = [data]
						}

					_this.domshow(doms,grid)

					}
				let parent_form = $(ui.draggable).parent('.tbodydata')
				if(ultype=='user'){parent_form=$(ui.helper).parents('#master_user')}
				if(parent_form.data('form')){
						let parent_data = JSON.parse(parent_form.data('form'));
						$.each(parent_data,(index,item)=>{
							if(item&&item.id ==id){
								parent_data.splice(index,1)
							};
						})
						parent_form.data('form',JSON.stringify(parent_data))

					}
					ui.draggable.remove()
			}
		})
	}
	// 排序
	_this.sortTabName = function(){
		$('.drawbox').find('.sortName').click(function(){
			let data = JSON.parse($(this).parent().next().data('form'));
			let ele = $(this).parent().next();
			let arr = [];
			arr = data.sort((item1,item2)=>item1.name.localeCompare(item2.name,'zh-CN'));
			_this.domshow(ele,arr)
		})
	}
	// 获取数据
	_this.getformdata = function(){
		let loadPanel = $('<div>').dxLoadPanel({
			message:'正在加载………',
			width:'222',
			visible:true
		}).appendTo('body')

		$.get($.config('apiUrl')+'shift/query?jobId='+_this.jobid+`&date=${moment(_this.startTime).format('YYYY-MM-DD')}`).then(res=>{
				if(res.errcode === 200){
					_this.user_show(res.data.employees)
					$(res.data.employees).each((index,item)=>{						
						item.shiftBig = 0;
						item.shiftSmall = 0;
						_this.users.push(item)
					})
					res.data.shifts.forEach(item=>{
						item.signIn = item.signIn?moment(item.signIn).format('HH:mm:ss'):'未签到';
						item.signOut = item.signOut?moment(item.signOut).format('HH:mm:ss'):'未签退';
					})
				return res.data.shifts}
			}).then(user=>{
				let show_emp = {};
				$(user).each((index,item)=>{
					item.employee.type = item.shift.id;
					item = Object.assign(item,item.employee)
					if(show_emp[item.shift.id]){
						show_emp[item.shift.id].push(item)
					}else{
						show_emp[item.shift.id]=[item]
					};
					item.employee.shiftBig =0;
					item.employee.shiftSmall = 0;
					_this.users.push(item)

				})

				$.get($.config('apiUrl')+'shift?_no_page=1').then(res=>{
				let appHtml = '';
				if(res.errcode === 200){
					let datatype = res.data;
					try{
					let job_list = _this.job_list.filter(item=>item.id==_this.jobid)[0].jobShifts
					job_list = job_list.sort((a,b)=>a.sort-b.sort);
					let roomData = [];
					job_list.forEach(item=>{
						datatype.forEach(it=>{
							if(it.id==item.shiftId)roomData.push(it)
						})
					}) 
					datatype = roomData
				}catch(er){
					alert('请分配工种班次')
					console.error('没有班次信息')
				}
					for(let a=0 ;a<datatype.length ;a++){
						appHtml += header(datatype[a].name,datatype[a].id,datatype.length)
					}
					page.content.find('#bodyfun').html(appHtml);
					_this.content_append();
					page.content.find('.drawbox').each(function(index,item){
						let topdata = (show_emp[$(this).data('type')]||[]).filter(it=>!it.isFix);
						let bottomdata = (show_emp[$(this).data('type')]||[]).filter(it=>it.isFix)
						_this.domshow($(item).find('.top_data .tbodydata'),topdata)
						_this.domshow($(item).find('.bottom_data .tbodydata'),bottomdata)
					})
					_this.sortTabName()
					loadPanel.remove()
				}else{
				new DevExpress.ui.notify({message:'服务错误,请联系管理员'},'warning',1500)
				}
			})
		})
	}

	$.get($.config('apiUrl')+'job?_no_page=1').then(res=>{
			if(res.errcode === 200){
			_this.jobid = res.data[0].id;
			_this.job_list = res.data
			toolbarfun(_this.startTime,res.data)
			return res.data
			}else{
				new DevExpress.ui.notify({message:'服务错误,请联系管理员'},'warning',1500)
			}
			}).then(resp=>{
				_this.getformdata()
			}).fail(err=>{
					new DevExpress.ui.notify({message:'服务错误,请联系管理员'},'warning',1500)
		})
	}

})

App.registerRoute({
	name:'shift_month',
	onLoad:function(context, $container){
		let page = new Page($container);
		page.crudLayout({title: '排班管理-月图'});

		let html_date = '<div  >'+
		'<div class="toolbar_box"></div>'+
		'<div style="width:100%;overflow:auto" class="table_box"></div></div>';

		page.content.html(html_date);
		let _this = this;
		_this.startTime = new Date();
		_this.jobtype = ''
		_this.shiftid = [];
		_this.append_tr = function(na,ar){
			let trhtml = `<tr><th class="text-center">${na}</th>`;
			$.each(ar,(index,item)=>{
				trhtml += `<td>${item}</td>`
			})
			trhtml+'</tr>'
			return trhtml
		} 
		_this.tbodyhtml = function(date){
		let year = moment(date).year();
		let month = moment(date).month()+1;
		let day = moment(`${year}-${month}-1`).day();
		let dayof = 28

		if(month===1||month===3||month===5||month===7||month===8||month===10||month==12){
			dayof = 31
		};

		if(month===4||month===6||month===9||month===11){
			dayof = 30
		};
		
		if(month===2&&moment(date).isLeapYear()){
			dayof = 29
		};

		
		let thead = function(){
			let headhtml = '<th width="80" class="text-center">日期</th>';
			for(let a=0;a< dayof;a++){
				headhtml += '<th width="60" class="text-center" data-id="'+(a+1)+'">'+(a+1)+'</th>'
			}
			return headhtml
		}

		let tbody = function(){
			let headhtml = '<th class="text-center">星期</th>';
			for(let a=0;a<dayof;a++){
				let daytext = '一';
				switch(day){
					case 2:daytext='二';break;
					case 3:daytext='三';break;
					case 4:daytext='四';break;
					case 5:daytext='五';break;
					case 6:daytext='六';break;
					case 7:daytext='日';break;
				}
				headhtml += '<td>'+daytext+'</td>'
				if(day === 7){
					day=0
				}
				day++
			}
			return headhtml
		}


			let table_box = '<table border="1" style="border-color:#eee;background:#f6f8f8;color:#58666e;text-align:center;width:100%;height:30px;line-height:30px;padding:0;border-collapse: collapse;min-width:1550px" id="printTable">'+
			'<thead ><tr>'+
			thead()+
			'</tr><tr>'+
			tbody()+
			'</tr>'+
			'<tbody class="bodydata"><tbody>'
			return table_box
		}

		_this.getData = function(){
			page.content.find('.table_box').html(_this.tbodyhtml(_this.startTime))
			page.content.find('th').each((index,item)=>{
				if($(item).data('id')){
					$(item).click(function(){
						let date = `${moment(_this.startTime).year()}-${moment(_this.startTime).month()+1}-${$(item).data('id')}`;
						location.href='#/employeeshift?date='+date
					}).css('cursor','pointer')
				}
			})

			let loadPanel = $('<div>').dxLoadPanel({
			message:'正在加载………',
			width:'222',
			visible:true
			}).appendTo('body')

			$.get($.config('apiUrl')+`shift/month?jobId=${_this.jobtype}&month=${moment(_this.startTime).month()+1}&year=${moment(_this.startTime).year()}`)
				.then(res=>{
					if(res.errcode === 200){
						let tr_body = ''
						$.each(res.data,(index,item)=>{
							tr_body += _this.append_tr(item.name,item.dayStatus)
						});
						page.content.find('.bodydata').html(tr_body)
						loadPanel.remove();
					}else{
					new DevExpress.ui.notify({message:'服务错误,请联系管理员'},'warning',1500)
					}
				})
				.fail(err=>{
					new DevExpress.ui.notify({message:'服务错误,请联系管理员'},'warning',1500)
				})

		}
		_this.toolbarfun = function(job){
				page.content.find('.toolbar_box').dxToolbar({
				items:[{
					widget:'setDateMonth',
					location:'before',
					options:{
						value:moment().format('YYYY-MM'),
						onValueChanged:function(e){
							_this.startTime = e;
							_this.getData()
						}
					}
				},
				// {
				// 	widget:'dxDateBox',
				// 	location:'before',
				// 	options:{
				// 		type:"date",
				// 		value:_this.startTime,
				// 		displayFormat: 'yyyy-MM',
				// 		dateSerializationFormat: "yyyy-MM-dd",
				// 		onValueChanged:function(e){
						
				// 		}
				// 	}
				// },
				{
					widget:'dxSelectBox',
					location:'before',
					options:{
						dataSource:job,
						displayExpr:'name',
						valueExpr:'id',
						value:job[0].id,
						onValueChanged:function(e){
							this.jobtype = e.value;
							_this.getData()
						}
					}

				},{
					widget:'dxButton',
					location:'before',
					options:{
						text:'打印',
						onClick:function(e){
							let table = document.getElementById('printTable');
							let newWin = window.open('');
							newWin.document.write(table.outerHTML);
							newWin.document.body.style.width='1550px'
							newWin.document.close();
							newWin.focus();
							newWin.print();
							newWin.close()
						}
					}
				},{
					widget:'dxButton',
					location:'after',
					options:{
						text:'返回',
						onClick:function(e){
							location.href='#/employeeshift'
						}
					}
				}]
			})
		}

		$.get($.config('apiUrl')+'job?_no_page=1').then(res=>{
				if(res.errcode === 200){
					_this.jobtype = res.data[0].id;
					setTimeout(()=>{_this.toolbarfun(res.data)},0)
					return res.data
				}else{
					new DevExpress.ui.notify({message:'服务错误,请联系管理员'},'warning',1500)
				}
			}).then(resp=>{
				_this.getData()
			})
		
	}
})

